package com.sinog.front.controller.basic;

import com.sinog.core.util.JsonUtil;
import com.sinog.core.utilbean.Constants;
import com.sinog.front.config.log.ControllerInterceptor;
import com.sinog.front.feign.biz.UserLoginCheckService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @desc 登陆请求页
 * @author zy
 * @date 2019年6月28日 15点51分
 */
@Slf4j
@Controller
public class LoginController {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private UserLoginCheckService userLoginCheckService;
    /**
     * 设置session过期时间
     */
    @Value("${server.servlet.session.timeout}")
    private Integer sessionTime;

    /**
     * 用户登录信息列表集合
     * @param pageIndex pageIndex
     * @param pageSize pageSize
     * @param account account
     * @param username username
     * @param loginState loginState
     * @return String
     */
    @RequestMapping("/basic/login/getLoginDetailsList")
    @ResponseBody
    public String getLoginDetailsList(Integer pageIndex,Integer pageSize,String account,String username,String loginState) {
        Map<String,Object> paramMap = new HashMap<>(16);
        paramMap.put("pageIndex",pageIndex);
        paramMap.put("pageSize",pageSize);
        paramMap.put("account",account);
        paramMap.put("username",username);
        paramMap.put("loginState",loginState);
        String text = JsonUtil.toText(paramMap);
        return userLoginCheckService.getLoginDetailsList(text);
    }

    /**
     * 账号异地登录方法处理
     * @param request request
     * @return boolean
     */
    @GetMapping("/front/checkUserState")
    @ResponseBody
    public String checkUserLoginState(HttpServletRequest request) {
        Date creationTime = ControllerInterceptor.timeout.get().get(request.getSession().getId());
        if(creationTime != null){
            long datePoor = getDatePoor(new Date(),creationTime);
            if(datePoor >= sessionTime) {
                request.getSession().setMaxInactiveInterval(1);
            } else {
                request.getSession().setMaxInactiveInterval(Math.toIntExact(sessionTime - datePoor));
            }
        }
        int maxInactiveInterval = request.getSession().getMaxInactiveInterval();
        log.info("session:{},有效期剩余{}毫秒",request.getSession().getId(),maxInactiveInterval);
        String sessionName = "userSession:";
        String userState = "userState:";
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Map<String,Object> paramMap = JsonUtil.toMap(JsonUtil.toText(authentication.getDetails()));
        String userName = JsonUtil.toText(authentication.getPrincipal()).replace("\"","");
        String redisSessionid = stringRedisTemplate.opsForValue().get(sessionName + userName);
        String redisUserState = stringRedisTemplate.opsForValue().get(userState + paramMap.get("sessionId").toString());
        if(null != redisSessionid) {
            if(null != redisUserState && Constants.NumberStr.NUM_STR_ONE.equals(redisUserState)) {
                // 登录超时
                if(Constants.StrFinalValue.ANONYMOUSUSER.equals(userName)) {
                    return Constants.StrFinalValue.TIMEOUR;
                    // 账号异地登录
                } else {
                    return Constants.StrFinalValue.REMOTELOGIN;
                }
            } else {
                if(null != redisSessionid && !redisSessionid.equals(paramMap.get("sessionId"))) {
                    stringRedisTemplate.opsForValue().set(sessionName + userName,paramMap.get("sessionId").toString());
                    stringRedisTemplate.expire(sessionName + userName,30,TimeUnit.MINUTES);
                    stringRedisTemplate.opsForValue().set(userState + redisSessionid,"1");
                    stringRedisTemplate.expire(userState + redisSessionid,30,TimeUnit.MINUTES);
                    stringRedisTemplate.opsForValue().set(userState + paramMap.get("sessionId").toString(),"0");
                    stringRedisTemplate.expire(userState + paramMap.get("sessionId").toString(),30,TimeUnit.MINUTES);
                }
            }
        } else if(null == redisSessionid) {
            stringRedisTemplate.opsForValue().set(sessionName + userName,paramMap.get("sessionId").toString());
            stringRedisTemplate.expire(sessionName + userName,30,TimeUnit.MINUTES);
            stringRedisTemplate.opsForValue().set(userState + paramMap.get("sessionId").toString(),"0");
            stringRedisTemplate.expire(userState + paramMap.get("sessionId").toString(),30,TimeUnit.MINUTES);
        }
        return Constants.SpecialChar.NUM_BLANK;
    }

    /**
     * 获取毫秒数
     * @param endDate endDate
     * @param nowDate nowDate
     * @return long
     */
    private long getDatePoor(Date endDate,Date nowDate) {
        //获取毫秒数
        long startTime = nowDate.getTime();
        //获取毫秒数
        long endTime = endDate.getTime();
        long timeDifference = endTime - startTime;
        return timeDifference / 1000;
    }
}